package com.doit.demo.day11;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @DATE 2022/2/28/13:20
 * @Author MDK
 * @Version 2021.2.2
 *
 * 使用Flink Table API 实现实时WordCount
 *
 **/
public class TableWordCount {
    public static void main(String[] args) throws Exception {
        //创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //StreamTableEnvironment将原来的StreamExecutionEnvironment包装起来（增强）
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);

        //创建普通的数据流
        DataStreamSource<String> lines = env.socketTextStream("linux01", 8888);
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] fields = value.split(",");
                return Tuple2.of(fields[0], Integer.parseInt(fields[1]));
            }
        });

        //将普通数据流变成带字段的表格
        Table table = tableEnvironment.fromDataStream(wordAndOne, "word,counts");
        Table tableRes = table.groupBy($("word")).select($("word"), $("counts").sum());

        DataStream<Tuple2<Boolean, Tuple>> retractStream = tableEnvironment.toRetractStream(tableRes, Types.TUPLE(Types.STRING,Types.INT));

        retractStream.print();

        env.execute();

    }
}
